﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RemoteManger
{
    /// <summary>
    /// 自定义的雪花算法，生成分布式ID
    /// </summary>
    public class SnowFlake
    {

        private static long workerId;//机器ID

        private static readonly int sequenceBits = 5;    //计数器字节数
        private static readonly long sequenceMask = -1L ^ -1L << sequenceBits; //一微秒内可以产生计数，如果达到该值则等到下一微妙在进行生成0-31 共32

        private static readonly int shardingKeyBits = 10; //库表标记占字节数
        private static readonly long maxShardingKey = -1L ^ -1L << shardingKeyBits; //库、表标记最大数 0-1023 共1024

        private static readonly int workerIdBits = 6;    //机器码字节数
        private static readonly long maxWorkerId = -1L ^ -1L << workerIdBits; //最大机器ID 0-63 共64个

        private static readonly int timestampBits = 41;  //时间戳字节数
        private static readonly long maxTimestamp = -1L ^ -1L << timestampBits; //最大时间戳

        private static readonly int shardingKeyShift = sequenceBits;                 //表标记的偏移量
        private static readonly int workerIdShift = sequenceBits + shardingKeyBits; //机器码数据左移位数，就是后面计数器占用的位数
        private static readonly int timestampShift = sequenceBits + shardingKeyBits + workerIdBits; //时间戳左移动位数就是机器码和计数器总字节数
        private static readonly int hidShift = sequenceBits + shardingKeyBits + workerIdBits + timestampBits; //高位左移

        private static long lastTimestamp = -1L;
        private static Dictionary<long, long> lastShardingKey = new Dictionary<long, long>();
        private static readonly object lockObj = new object();

        /// <summary>
        /// 自定义的雪花算法，生成分布式ID
        /// </summary>
        static SnowFlake()
        {
            workerId = 1;//机器码0-63 最多64个机器
        }

        /// <summary>
        /// 生成唯一ID
        /// </summary>
        /// <returns></returns>
        public static long GenerateId()
        {
            return Next(new Random().Next(1024));
        }

        /// <summary>
        /// 生成唯一ID
        /// </summary>
        /// <param name="id">雪花ID</param>
        /// <returns></returns>
        public static long GenerateId(long id)
        {
            return Next(GetShardingKey(id));
        }

        /// <summary>
        /// 获取分表的标识
        /// </summary>
        /// <param name="id">雪花ID</param>
        /// <returns></returns>
        public static int GetShardingKey(long id)
        {
            long key = id >> shardingKeyShift & maxShardingKey;
            return (int)key;
        }

        /// <summary>
        /// 获取机器标识
        /// </summary>
        /// <param name="id">雪花ID</param>
        /// <returns></returns>
        public static int GetWorkerId(long id)
        {
            long key = id >> workerIdShift & maxWorkerId;
            return (int)key;
        }

        /// <summary>
        /// 生成唯一ID（ 时间41位 + 机器码6位 + 表标记8位 + 计数器5位）
        /// </summary>
        /// <param name="shardingKey">库/表标记,从1开始</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private static long Next(long shardingKey)
        {
            lock (lockObj)
            {
                long _shardingKey = shardingKey;
                if (_shardingKey > maxShardingKey || _shardingKey < 0)
                {
                    throw new Exception(string.Format("Sharding key can't be greater than {0} or less than 0 ", maxShardingKey));
                }
                long timestamp = TimeGen();
                if (lastTimestamp == timestamp)//同一微秒中生成ID
                {
                    if (lastShardingKey.ContainsKey(_shardingKey))
                    {
                        lastShardingKey[_shardingKey] = lastShardingKey[_shardingKey] + 1 & sequenceMask; //用&运算计算该微秒内产生的计数是否已经到达上限
                        if (lastShardingKey[_shardingKey] == 0)
                        {
                            timestamp = TillNextMillis(lastTimestamp);//一微妙内产生的ID计数已达上限，等待下一微妙
                        }
                    }
                }
                else//不同秒生成ID
                {
                    lastShardingKey = new Dictionary<long, long>();
                }
                if (!lastShardingKey.ContainsKey(_shardingKey))
                {
                    lastShardingKey.Add(_shardingKey, 0);//保存当前表标记
                }
                if (timestamp < lastTimestamp) //如果当前时间戳比上一次生成ID时时间戳还小，抛出异常，因为不能保证现在生成的ID之前没有生成过
                {
                    throw new Exception(string.Format("Clock moved backwards.  Refusing to generate id for {0} milliseconds", lastTimestamp - timestamp));
                }
                lastTimestamp = timestamp; //把当前时间戳保存为最后生成ID的时间戳
                long nextId = 1L << hidShift | timestamp << timestampShift | workerId << workerIdShift | _shardingKey << shardingKeyShift | lastShardingKey[_shardingKey];
                return nextId;
            }
        }

        /// <summary>
        /// 获取下一秒时间戳
        /// </summary>
        /// <param name="lastTimestamp"></param>
        /// <returns></returns>
        private static long TillNextMillis(long lastTimestamp)
        {
            long timestamp = TimeGen();
            while (timestamp <= lastTimestamp)
            {
                timestamp = TimeGen();
            }
            return timestamp;
        }

        /// <summary>
        /// 生成当前时间戳,精确到秒
        /// </summary>
        /// <returns></returns>
        private static long TimeGen()
        {
            long timestamp = (long)(DateTime.UtcNow - new DateTime(2021, 12, 22, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
            if (timestamp > maxTimestamp || timestamp < 0)
            {
                throw new Exception(string.Format("Time stamp can't be greater than {0} or less than 0 ", maxTimestamp));
            }
            return timestamp;
        }

    }
}
